package com.gitee.jmliu1983.javautils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
// 

/**
 * @author jianmin.liu
 * 来源：https://yiyan.baidu.com/share/23GxfG9mPm
 * 压缩和解压字符串
 * 
 */
public class Compress {
    public static String decompressString(byte[] compressed) throws IOException {  

        if (compressed == null || compressed.length == 0) {  
            return "";  
        }  

        ByteArrayInputStream bais = new ByteArrayInputStream(compressed);  
        GZIPInputStream gzis = new GZIPInputStream(bais);  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  

        byte[] buffer = new byte[1024];  

        int len;  

        while ((len = gzis.read(buffer)) > 0) {  
            baos.write(buffer, 0, len);  
        }  
        gzis.close();  
        return new String(baos.toByteArray());  

    } 
    
    public static byte[] compressString(String str) throws IOException {  
        if (str == null || str.length() == 0) {  
            return new byte[0];  
        }  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        GZIPOutputStream gzos = new GZIPOutputStream(baos);  
        gzos.write(str.getBytes());  
        gzos.close();  
        return baos.toByteArray();  

    }  
}
